package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.leaseException;
import com.atguigu.lease.common.login.LoginUser;
import com.atguigu.lease.common.login.LoginUserHolder;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.mapper.SystemUserMapper;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.wf.captcha.SpecCaptcha;
import jakarta.annotation.Resource;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
//  注入redis容器
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private SystemUserMapper systemUserMapper;

    @Override
    public CaptchaVo getCaptcha() {
//      创建图像化对象
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
//      获得即将存在redis内的图象化内容
        String code = specCaptcha.text().toLowerCase();
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID();

        stringRedisTemplate.opsForValue().set(key, code,RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);
//      获得返回前端的(字符串)图象化内容
        String captcha = specCaptcha.toBase64();
        return new CaptchaVo(captcha,key);
    }

    @Override
    public String login(LoginVo loginVo) {
//      1.判断captchaCode是否为空，若为空，则直接响应验证码为空；若不为空进行下一步判断。
        if(loginVo.getCaptchaCode()==null){
            throw new leaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
//      获得存在redis内的图象化内容
        String code = stringRedisTemplate.opsForValue().get(loginVo.getCaptchaKey());
//      2.根据`captchaKey`从Redis中查询之前保存的`code`，若查询出来的`code`为空，则直接响应`验证码已过期`；若不为空进行下一步判断。
        if(code==null){
            throw new leaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
//      3.比较`captchaCode`和`code`，若不相同，则直接响应`验证码不正确`；若相同则进行下一步判断。
        if (!(loginVo.getCaptchaCode().toLowerCase().equals(code))){
            throw new leaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
//      4.根据`username`查询数据库，若查询结果为空，则直接响应`账号不存在`；若不为空则进行下一步判断。
        String username = loginVo.getUsername();
        SystemUser systemUser = systemUserMapper.selectOneName(username);
        if(systemUser==null){
            throw new leaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
//      5.查看用户状态，判断是否被禁用，若禁用，则直接响应`账号被禁`；若未被禁用，则进行下一步判断。
        if(systemUser.getStatus()== BaseStatus.DISABLE){
            throw new leaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
//      6.比对`password`和数据库中查询的密码，若不一致，则直接响应`账号或密码错误`，若一致则进行入最后一步。
        if (!systemUser.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword()))) {
            throw new leaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
//      7.创建JWT，并响应给浏览器。
        return JwtUtil.getToken(systemUser.getId(),systemUser.getUsername());
    }

    @Override
    public SystemUserInfoVo getinfo() {
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        SystemUser systemUser = systemUserMapper.selectById(loginUser.getUserId());
        SystemUserInfoVo vo = new SystemUserInfoVo();
        vo.setName(systemUser.getName());
        vo.setAvatarUrl(systemUser.getAvatarUrl());
        return vo;
    }
}
